/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ServerClient;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 *
 * @author TUAN ANH
 */
public class Client implements TranferData{
    private Socket client;
    private BufferedReader bufferedReader;
    private DataOutputStream dataOutputStream;
    private int port;
    private String localhost;
    public  Client(String localhost,int port){
        this.localhost = localhost;
        this.port = port;
    }
    @Override
    public void initConnection()  throws Exception{
//        throw new UnsupportedOperationException("Not supported yet.");
        client = new Socket(localhost, port);
        bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        dataOutputStream = new DataOutputStream(client.getOutputStream());
    }

    @Override
    public String receiveData()  {
//        throw new UnsupportedOperationException("Not supported yet.");
        try{
        String receiveData = bufferedReader.readLine();
        return receiveData;
        }catch(Exception ex){
            System.out.println(ex.toString());
            return null;
        }
        
    }

    @Override
    public void sentData(String data)  {
//        throw new UnsupportedOperationException("Not supported yet.");
//        int i = 0;
        try{
        for(int i=0;i<data.length();i++){
            dataOutputStream.write((byte) data.charAt(i));
        }
        dataOutputStream.write(13);
        dataOutputStream.flush();
        }catch(Exception exc){
            System.out.println(exc.toString());
        }
    }

    @Override
    public void close() {
        try{
        client.close();
        bufferedReader.close();
        dataOutputStream.close();
        }catch(Exception ex){
            System.out.println(ex.toString());
        }
//        throw new UnsupportedOperationException("Not supported yet.");
    }
    
}
